/*
	File:    	ScreenUtilsOMX.c
	Package: 	Apple CarPlay Communication Plug-in.
	Abstract: 	n/a 
	Version: 	n/a
	
	Disclaimer: IMPORTANT: This Apple software is supplied to you, by Apple Inc. ("Apple"), in your
	capacity as a current, and in good standing, Licensee in the MFi Licensing Program. Use of this
	Apple software is governed by and subject to the terms and conditions of your MFi License,
	including, but not limited to, the restrictions specified in the provision entitled ”Public 
	Software”, and is further subject to your agreement to the following additional terms, and your 
	agreement that the use, installation, modification or redistribution of this Apple software
	constitutes acceptance of these additional terms. If you do not agree with these additional terms,
	please do not use, install, modify or redistribute this Apple software.
	
	Subject to all of these terms and in consideration of your agreement to abide by them, Apple grants
	you, for as long as you are a current and in good-standing MFi Licensee, a personal, non-exclusive 
	license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, 
	reproduce, and modify the Apple Software in source form, and to use, reproduce, modify, and 
	redistribute the Apple Software, with or without modifications, in binary form. While you may not 
	redistribute the Apple Software in source form, should you redistribute the Apple Software in binary
	form, you must retain this notice and the following text and disclaimers in all such redistributions
	of the Apple Software. Neither the name, trademarks, service marks, or logos of Apple Inc. may be
	used to endorse or promote products derived from the Apple Software without specific prior written
	permission from Apple. Except as expressly stated in this notice, no other rights or licenses, 
	express or implied, are granted by Apple herein, including but not limited to any patent rights that
	may be infringed by your derivative works or by other works in which the Apple Software may be 
	incorporated.  
	
	Unless you explicitly state otherwise, if you provide any ideas, suggestions, recommendations, bug 
	fixes or enhancements to Apple in connection with this software (“Feedback”), you hereby grant to
	Apple a non-exclusive, fully paid-up, perpetual, irrevocable, worldwide license to make, use, 
	reproduce, incorporate, modify, display, perform, sell, make or have made derivative works of,
	distribute (directly or indirectly) and sublicense, such Feedback in connection with Apple products 
	and services. Providing this Feedback is voluntary, but if you do provide Feedback to Apple, you 
	acknowledge and agree that Apple may exercise the license granted above without the payment of 
	royalties or further consideration to Participant.
	
	The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR 
	IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY 
	AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR
	IN COMBINATION WITH YOUR PRODUCTS.
	
	IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES 
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
	PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION 
	AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT
	(INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE 
	POSSIBILITY OF SUCH DAMAGE.
	
	Copyright (C) 2013-2016 Apple Inc. All Rights Reserved.
*/

#include "ScreenUtils.h"

#include "CFUtils.h"
#include "CommonServices.h"
#include "DebugServices.h"
#include "MiscUtils.h"

#include CF_HEADER
#include CF_RUNTIME_HEADER
#include LIBDISPATCH_HEADER

#include <bcm_host.h>
#include <ilclient.h>

//===========================================================================================================================
//	ScreenStream
//===========================================================================================================================

#define kVideoTimeoutMs					1000
#define kVideoPort_DecoderInput			130
#define kVideoPort_DecoderOutput		131
#define kVideoPort_RendererInput		90

typedef struct ScreenStreamImp *			ScreenStreamImpRef;
struct ScreenStreamImp
{
	CFRuntimeBase		base;					// CF type info. Must be first.
	void *				delegateContext;		// Context for the session delegate
	uint8_t *			annexBHeaderPtr;		// Ptr to H.264 Annex-B header.
	size_t				annexBHeaderLen;		// Number of bytes in the H.264 Annex-B header.
	Boolean				annexBHeaderWritten;	// True if we've written the full Annex-B header to the decoder.
	size_t				nalSizeHeader;			// Number of bytes in the size before each NAL unit.
	int					widthPixels;			// Width of the screen in pixels.
	int					heightPixels;			// Height of the screen in pixels.
	ILCLIENT_T *		videoClient;
	COMPONENT_T *		videoDecoder;
	COMPONENT_T *		videoRenderer;
	COMPONENT_T *		videoComponents[ 3 ];
	TUNNEL_T			videoTunnels[ 2 ];
	Boolean				videoPipelineSetup;
	Boolean				videoPortSettingsChanged;
	uint32_t			videoFrameCount;
};

#define _ScreenStreamGetImp( STREAM )		( (ScreenStreamImpRef) ScreenStreamGetContext( (STREAM) ) )

//===========================================================================================================================
//	Logging
//===========================================================================================================================

ulog_define( ScreenStream, kLogLevelNotice, kLogFlags_Default, "ScreenStream", NULL );
#define ss_dlog( LEVEL, ... )		dlogc( &log_category_from_name( ScreenStream ), (LEVEL), __VA_ARGS__ )
#define ss_ulog( LEVEL, ... )		ulog( &log_category_from_name( ScreenStream ), (LEVEL), __VA_ARGS__ )

//===========================================================================================================================
//	ScreenStreamInitialize
//===========================================================================================================================

OSStatus	ScreenStreamInitialize( ScreenStreamRef inStream)
{
	OSStatus				err;
	ScreenStreamImpRef		me;
	
	require_action( ScreenStreamGetContext( inStream ) == NULL, exit, err = kAlreadyInitializedErr );
	
	me = (ScreenStreamImpRef) calloc( 1, sizeof( *me ) );
	require_action( me, exit, err = kNoMemoryErr );
	
	ScreenStreamSetContext( inStream, me );
	err = kNoErr;
	
exit:
	return( err );
}

//===========================================================================================================================
//	_ScreenStreamFinalize
//===========================================================================================================================

void	ScreenStreamFinalize( ScreenStreamRef inStream )
{
	ScreenStreamImpRef const		me = _ScreenStreamGetImp( inStream );
	
	require( me, exit );
	
	check( !me->annexBHeaderPtr );
	check( !me->videoClient );
	check( !me->videoPipelineSetup );
	ScreenStreamSetContext( inStream, NULL );
	free( me );
	
exit:
	LogCategory_Remove( &log_category_from_name( ScreenStream ) );
}

//===========================================================================================================================
//	_ScreenStreamSetProperty
//===========================================================================================================================

/*
 0164001f ffe10013 6764001f ac56502d 0f69b810 10103682 21196001 000528ee 15c9c0
 01: version: 1
 64: profile_idc: high
 00: constraint
 1f: level_idc: 3.1
 ff: 0xFC | (length - 1)
 e1: 0xE0 | numOfSPSs
 0013:
 67: SPS
 64: high
 00: constraint
 1f: level 3.1
 ...
 ac56502d 0f69b810 10103682 211960
 01: numOfPPS
 0005:
 28ee 15c9c0
 */

void _DisplayAVCC( const uint8_t * avccPtr, size_t avccLen );
void _DisplayAVCC( const uint8_t * avccPtr, size_t avccLen )
{
	if (avccLen >= 4)
		ss_ulog( kLogLevelNotice, "AVCC %02X %02X %02X\n", avccPtr[1], avccPtr[2], avccPtr[3] );
}

//===========================================================================================================================
//	ScreenStreamSetDelegateContext
//===========================================================================================================================

void ScreenStreamSetDelegateContext( ScreenStreamRef inStream, void* inContext )
{
	ScreenStreamImpRef const me = _ScreenStreamGetImp( inStream );
	me->delegateContext = inContext;
}

//===========================================================================================================================
//	ScreenStreamSetWidthHeight
//===========================================================================================================================

void ScreenStreamSetWidthHeight( ScreenStreamRef inStream, uint32_t width, uint32_t height )
{
	ScreenStreamImpRef const me = _ScreenStreamGetImp( inStream );
	me->widthPixels = width;
	me->heightPixels = height;
}

//===========================================================================================================================
//	ScreenStreamSetViewArea
//===========================================================================================================================

void ScreenStreamSetViewArea( ScreenStreamRef inStream, uint32_t width, uint32_t height, uint32_t originX, uint32_t originY )
{
	ScreenStreamImpRef const me = _ScreenStreamGetImp( inStream );
	ss_ulog( kLogLevelNotice, "Screen Stream Set View Area: %d %d %d %d\n", width, height, originX, originY);
}

//===========================================================================================================================
//	ScreenStreamSetAVCC
//===========================================================================================================================

OSStatus ScreenStreamSetAVCC( ScreenStreamRef inStream, const uint8_t* avccPtr, size_t avccLen )
{
	OSStatus err = kNoErr;
	
	ScreenStreamImpRef const me = _ScreenStreamGetImp( inStream );
	_DisplayAVCC( avccPtr, avccLen );
	uint8_t *			headerPtr;
	size_t				headerLen;
	size_t				nalSizeHeader;
	
	err = H264ConvertAVCCtoAnnexBHeader( avccPtr, avccLen, NULL, 0, &headerLen, NULL, NULL );
	require_noerr( err, exit );
	
	headerPtr = (uint8_t *) malloc( headerLen );
	require_action( headerPtr, exit, err = kNoMemoryErr );
	err = H264ConvertAVCCtoAnnexBHeader( avccPtr, avccLen, headerPtr, headerLen, &headerLen, &nalSizeHeader, NULL );
	if( err )
		free( headerPtr );
	require_noerr( err, exit );
	
	if( me->annexBHeaderPtr )
		free( me->annexBHeaderPtr );
	me->annexBHeaderPtr		= headerPtr;
	me->annexBHeaderLen		= headerLen;
	me->nalSizeHeader		= nalSizeHeader;
	me->annexBHeaderWritten = false;
exit:
	return( err );
}

//===========================================================================================================================
//	ScreenStreamStart
//===========================================================================================================================

OSStatus   ScreenStreamStart( ScreenStreamRef inStream, AirPlayStreamType inStreamType, CFStringRef inScreenUUID )
{
	ScreenStreamImpRef const		me = _ScreenStreamGetImp( inStream );
	OSStatus							err;
	OMX_VIDEO_PARAM_PORTFORMATTYPE		format;

	(void)inStreamType;
	(void)inScreenUUID;	
	ss_ulog( kLogLevelNotice, "Screen stream starting...\n" );
	
	bcm_host_init();
	
	me->videoClient = ilclient_init();
	require_action( me->videoClient, exit, err = kUnknownErr );
	
	err = OMX_Init();
	require_noerr( err, exit );
	
	err = ilclient_create_component( me->videoClient, &me->videoDecoder, "video_decode",  ILCLIENT_DISABLE_ALL_PORTS | ILCLIENT_ENABLE_INPUT_BUFFERS );
	require_noerr( err, exit );
	me->videoComponents[ 0 ] = me->videoDecoder;
	
	err = ilclient_create_component( me->videoClient, &me->videoRenderer, "video_render", ILCLIENT_DISABLE_ALL_PORTS );
	require_noerr( err, exit );
	me->videoComponents[ 1 ] = me->videoRenderer;
	
	set_tunnel( &me->videoTunnels[ 0 ], me->videoDecoder, kVideoPort_DecoderOutput,	me->videoRenderer, kVideoPort_RendererInput );

	err = ilclient_change_component_state( me->videoDecoder, OMX_StateIdle );
	require_noerr( err, exit );
	
	memset( &format, 0, sizeof( format ) );
	format.nSize				= sizeof( format );
	format.nVersion.nVersion	= OMX_VERSION;
	format.nPortIndex			= kVideoPort_DecoderInput;
	format.eCompressionFormat	= OMX_VIDEO_CodingAVC;
	err = OMX_SetParameter( ILC_GET_HANDLE( me->videoDecoder ), OMX_IndexParamVideoPortFormat, &format );
	require_noerr( err, exit );
	
	err = ilclient_enable_port_buffers( me->videoDecoder, kVideoPort_DecoderInput, NULL, NULL, NULL );
	require_noerr( err, exit );
	
	err = ilclient_change_component_state( me->videoDecoder, OMX_StateExecuting );
	require_noerr( err, exit );
	
	me->videoPipelineSetup = true;
	ss_ulog( kLogLevelNotice, "Screen stream started\n" );
	
exit:
	if( err )
	{
		ss_ulog( kLogLevelError, "### Start screen stream failed: %#m\n", err );
		ScreenStreamStop( inStream );
	}
	return( err );
}

//===========================================================================================================================
//	ScreenStreamStop
//===========================================================================================================================

void	ScreenStreamStop( ScreenStreamRef inStream )
{
	ScreenStreamImpRef const		me = _ScreenStreamGetImp( inStream );
	OSStatus					err;
	OMX_BUFFERHEADERTYPE *		buf;
	
	DEBUG_USE_ONLY( err );
	
	ss_ulog( kLogLevelNotice, "Screen stream stopping...\n" );
	
	if( me->videoPipelineSetup )
	{
		buf = ilclient_get_input_buffer( me->videoDecoder, kVideoPort_DecoderInput, 1 );
		check( buf );
		if( buf )
		{
			buf->nFilledLen	= 0;
			buf->nOffset	= 0;
			buf->nFlags		= OMX_BUFFERFLAG_TIME_UNKNOWN | OMX_BUFFERFLAG_EOS;
			err = OMX_EmptyThisBuffer( ILC_GET_HANDLE( me->videoDecoder ), buf );
			check_noerr( err );
		}
		
		ilclient_wait_for_event( me->videoRenderer, OMX_EventBufferFlag, kVideoPort_RendererInput, 0, 
			OMX_BUFFERFLAG_EOS, 0, ILCLIENT_BUFFER_FLAG_EOS, kVideoTimeoutMs );
		ilclient_flush_tunnels( me->videoTunnels, 0 );
		ilclient_disable_port_buffers( me->videoDecoder, kVideoPort_DecoderInput, NULL, NULL, NULL );
	}
	
	ilclient_disable_tunnel( &me->videoTunnels[ 0 ] );
	ilclient_teardown_tunnels( me->videoTunnels );
	ilclient_state_transition( me->videoComponents, OMX_StateIdle );
	ilclient_state_transition( me->videoComponents, OMX_StateLoaded );
	ilclient_cleanup_components( me->videoComponents );
	OMX_Deinit();
	if( me->videoClient )
	{
		ilclient_destroy( me->videoClient );
		me->videoClient = NULL;
	}
	bcm_host_deinit();
	ForgetMem( &me->annexBHeaderPtr );
	
	ss_ulog( kLogLevelNotice, "Screen stream stopped\n" );
}

//===========================================================================================================================
//	ScreenStreamProcessData
//===========================================================================================================================

OSStatus ScreenStreamBuffer( ScreenStreamImpRef const me, OMX_BUFFERHEADERTYPE ** inOutBuf, const uint8_t* inData, size_t inLen );
OSStatus ScreenStreamBuffer( ScreenStreamImpRef const me, OMX_BUFFERHEADERTYPE ** inOutBuf, const uint8_t* inData, size_t inLen ) {
	OSStatus					err;
	OMX_BUFFERHEADERTYPE *		buf = *inOutBuf;

	do {
		if (!buf) {
			buf = ilclient_get_input_buffer( me->videoDecoder, kVideoPort_DecoderInput, 1 );
			require_action( buf, exit, err = kNoResourcesErr );
			buf->nFilledLen = 0;
		}
		size_t free = buf->nAllocLen - buf->nFilledLen;
		if( inLen <= free )
			break;
		memcpy( &buf->pBuffer[ buf->nFilledLen ], inData, free );
		inData += free;
		inLen -= free;
		buf->nFilledLen = buf->nAllocLen;
		buf->nFlags = 0;
		err = OMX_EmptyThisBuffer( ILC_GET_HANDLE( me->videoDecoder ), buf );
		buf = NULL;
		require_noerr( err, exit );
	} while ( inLen );
	memcpy( &buf->pBuffer[ buf->nFilledLen ], inData, inLen );
	buf->nFilledLen += inLen;
exit:
	*inOutBuf = buf;
	return err;
}

OSStatus
	ScreenStreamProcessData( 
		ScreenStreamRef				inStream,
		const uint8_t *				inData, 
		size_t						inLen, 
		uint64_t					inDisplayTicks, 
		CFDictionaryRef				inOptions, 
		ScreenStreamCompletion_f	inCompletion, 
		void *						inContext )
{
	ScreenStreamImpRef const		me = _ScreenStreamGetImp( inStream );
	OSStatus					err;
	const uint8_t *				src;
	const uint8_t *				end;
	const uint8_t *				nalPtr;
	size_t						nalLen;
	OMX_BUFFERHEADERTYPE *		buf = NULL;
	const uint8_t				startCodePrefix[4] = { 0x00, 0x00, 0x00, 0x01 };//H.264 zero_byte and start_code_prefix_one_3bytes, see H.264 Annex B, B.1.1
	
	(void) inDisplayTicks;
	(void) inOptions;
	
	if( !me->annexBHeaderWritten )
	{
		err = ScreenStreamBuffer( me, &buf, me->annexBHeaderPtr, me->annexBHeaderLen );
		require_noerr( err, exit );
		me->annexBHeaderWritten = true;
	}
	
	src = inData;
	end = src + inLen;
	while( H264GetNextNALUnit( src, end, me->nalSizeHeader, &nalPtr, &nalLen, &src ) == kNoErr )
	{
		err = ScreenStreamBuffer( me, &buf, startCodePrefix, sizeof( startCodePrefix ) );
		require_noerr( err, exit );
		err = ScreenStreamBuffer( me, &buf, nalPtr, nalLen );
		require_noerr( err, exit );
	}
	buf->nFlags = OMX_BUFFERFLAG_ENDOFFRAME;
	err = OMX_EmptyThisBuffer( ILC_GET_HANDLE( me->videoDecoder ), buf );
	buf = NULL;
	require_noerr( err, exit );
	
	if( !me->videoPortSettingsChanged )
	{
		err = ilclient_remove_event( me->videoDecoder, OMX_EventPortSettingsChanged, kVideoPort_DecoderOutput, 0, 0, 1 );
		if( !err )
		{
			ss_ulog( kLogLevelNotice, "Screen stream tunnel setting up after frame %u...\n", me->videoFrameCount );
			
			err = ilclient_setup_tunnel( &me->videoTunnels[ 0 ], 0, 0 );
			require_noerr( err, exit );
			
			ilclient_change_component_state( me->videoRenderer, OMX_StateExecuting );
			me->videoPortSettingsChanged = true;
			
			ss_ulog( kLogLevelNotice, "Screen stream tunnel setup done\n" );
		}
	}
	err = kNoErr;
	
exit:
	if( buf )
	{
		buf->nFilledLen = 0;
		buf->nOffset	= 0;
		buf->nFlags		= OMX_BUFFERFLAG_TIME_UNKNOWN;
		OMX_EmptyThisBuffer( ILC_GET_HANDLE( me->videoDecoder ), buf );
	}
	if( inCompletion ) inCompletion( inContext );
	return( err );
}
